package com.gt.filter;

import com.alibaba.fastjson.JSONObject;
import com.gt.threadlocal.RequestMapHolder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * wjh
 * 2021/8/30
*/
@Slf4j
public class RequestWrapperFilter extends OncePerRequestFilter {

    String[] excludeUrl = new String[]{"/luckyDraw/uploadPic","/scan/uploadPic"};

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        String path = request.getServletPath();
        for (String url : excludeUrl) {
            if (path.startsWith(url)) {
                return true;
            }
        }
        return false;
    }
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("RequestWrapperFilter请求地址:{}", MDC.get("uri"));
        JSONObject reqJson = new JSONObject();
        // 生成替代的ServletRequest 解决body无法重复读取的问题
        MultiReadHttpServletRequestWrapper requestWrapper = new MultiReadHttpServletRequestWrapper((HttpServletRequest) request);
        Set<String> keySet = request.getParameterMap().keySet();
        for (String key : keySet) {
            String[] results = request.getParameterMap().get(key);
            if(results.length == 1){
                reqJson.put(key,requestWrapper.getParameter(key)) ;
            }else if (results.length > 1) {
                reqJson.put(key,requestWrapper.getParameterValues(key)) ;
            }
        }
        RequestMapHolder.setRequestMapJson(reqJson);
        chain.doFilter(requestWrapper, response);
        RequestMapHolder.removeRequestMapJson();
    }

}
